package com.arcaneshift.model.validators;

import com.arcaneshift.manager.action.game.SpellCardManager;
import com.arcaneshift.manager.interfaces.ISpellCardManager;
import com.arcaneshift.model.action.game.SpellCard;
import com.arcaneshift.model.validators.abstracts.AbstractSimpleValidator;
import com.arcaneshift.security.errors.CardError;
import com.arcaneshift.security.exceptions.CardException;
import com.common.security.abstracts.AbstractError;
import com.common.security.abstracts.AbstractException;
import com.common.security.abstracts.AbstractRuntimeException;
import com.common.security.exceptions.ManagerException;

public class SpellCardValidator extends AbstractSimpleValidator<SpellCard> {

	private ISpellCardManager spellManager = new SpellCardManager();
	
	@Override
	public boolean validate(SpellCard item) {
		try {
			if (item.getName() == null) {
				error = new CardError(CardError.NO_NAME_PROVIDED);
				return false;
			}
			
			SpellCard card = spellManager.getSpellCard(item.getName());
			item.setId(card.getId());
			
			return true;
		} catch (ManagerException managerException) {
			error = new CardError(AbstractError.DATABASE_ERROR);
			return false;
		} catch (CardException cardException) {
			error = error(cardException);
			return false;
		}
	}
	
	private CardError error(AbstractRuntimeException exception) {
		switch (exception.getCode()) {
			case CardException.CARD_NOT_FOUND: {
				return new CardError(CardError.CARD_NOT_FOUND);
			}
			case CardException.MULTIPLE_CARDS_FOUND: {
				return new CardError(AbstractError.DATABASE_ERROR);
			}
			default: {
				return new CardError(AbstractException.ERROR_NOT_FOUND);
			}
		}
	}
}
